package com.zbb.order.service.Impl;

import com.google.gson.Gson;
import com.zbb.base.model.Result;
import com.zbb.base.util.RedisUtil;
import com.zbb.order.feignclient.UserServiceClient;
import com.zbb.order.model.po.User;
import com.zbb.order.service.ExitUserInfoService;
import com.zbb.order.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ExitUserInfoServiceImpl implements ExitUserInfoService {
    public static final String USERINFO = "userInfo:";

    @Autowired
    UserServiceClient userServiceClient;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public Result updateUser(User userVo) {
        User user = userServiceClient.querytUser(userVo.getId());
        user.setUserName(userVo.getUserName());
        user.setPersonalSignature(userVo.getPersonalSignature());
        user.setPhotoUrl(userVo.getPhotoUrl());
        user.setSchoolName(userServiceClient.selectSchoolnfo(user.getSchoolId()));
        user.setCampusName(userServiceClient.selectSchoolnfo(user.getCampusId()));
        userServiceClient.updateUser(user);
        Gson gson = new Gson();
        String userJson = gson.toJson(user);
        redisUtil.set(USERINFO+user.getId(),userJson,86400);
        return Result.ok();
    }

    @Override
    public User getUserInfo() {
        User user = SecurityUtil.getUser();
        Gson gson = new Gson();
        String userJson = (String) redisUtil.get(USERINFO+user.getId());
        if (!(userJson == null)){
            User userinfo = gson.fromJson(userJson, User.class);
            return userinfo;
        }
        User user2 = userServiceClient.querytUser(user.getId());
        user2.setSchoolName(userServiceClient.selectSchoolnfo(user.getSchoolId()));
        user2.setCampusName(userServiceClient.selectSchoolnfo(user.getCampusId()));
        String jsonStr = gson.toJson(user2);
        redisUtil.set(USERINFO+user.getId(),jsonStr,86400);
        return user2;
    }

    @Override
    public void doLogout(String userId) {
        redisUtil.del(USERINFO+userId);
    }
}
